﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace MobileAPI.Common
{

    /// <summary>
    /// 使用 GZip 压缩和解压
    /// </summary>
    public static class GZipUtils
    {

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static byte[] Compress(byte[] bytes)
        {

            if (bytes == null)
            {
                return null;
            }

            byte[] dst = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    zip.Write(bytes, 0, bytes.Length);
                    zip.Close();
                }
                dst = ms.ToArray();
            }
            return dst;
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] bytes)
        {
            if (bytes == null)
            {
                return null;
            }

            byte[] src = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream gs = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress, true))
                {
                    // 从压缩流中读出所有数据
                    byte[] buff = new byte[4096];
                    int n;
                    while ((n = gs.Read(buff, 0, buff.Length)) != 0)
                    {
                        ms.Write(buff, 0, n);
                    }
                    gs.Close();
                }
                src = ms.ToArray();
            }
            return src;
        }
    }
}
